package hbasecli.controller;

import cn.hutool.core.util.StrUtil;
import hbasecli.hbase.HbaseDao;
import hbasecli.hbase.HbaseTable;
import hbasecli.param.CreateTable;
import hbasecli.param.DeleteTable;
import hbasecli.param.ListTable;
import hbasecli.resp.Resp;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

import static cn.hutool.core.collection.CollUtil.isEmpty;
import static cn.hutool.core.util.BooleanUtil.isTrue;
import static cn.hutool.core.util.StrUtil.isBlankIfStr;
import static hbasecli.resp.Resp.failure;
import static hbasecli.resp.Resp.success;

@RestController
public class TableController {

    @Resource
    private HbaseDao hbaseDao;

    @PostMapping("/api/listTable")
    public Resp<List<HbaseTable>> listTable(@RequestBody ListTable param) {
        return success(hbaseDao.listTable(param));
    }

    @PostMapping("/api/createTable")
    public Resp<Boolean> createTable(@RequestBody CreateTable param) {
        String tableName = param.getTableName();
        if (isBlankIfStr(tableName)) {
            return failure("表名不可以为空");
        }
        List<String> families = param.getFamilies();
        if (isEmpty(families)) {
            return failure("至少需要一个列族");
        }
        Boolean deleteIfExists = param.getDeleteIfExists();
        return success(hbaseDao.createTable(tableName, families, isTrue(deleteIfExists)));
    }

    @PostMapping("/api/deleteTable")
    public Resp<Boolean> deleteTable(@RequestBody DeleteTable param) {
        List<String> tableNames = param.getTableNames();
        if (isEmpty(tableNames)) {
            return failure("至少需要一个表名");
        }
        for (String tableName : tableNames) {
            if (isBlankIfStr(tableName)) {
                return failure("表名不可以为空");
            }
        }
        return success(hbaseDao.deleteTable(tableNames));
    }
}
